<template>
    <div class="system-user-dialog-container">
      <el-dialog :close-on-click-modal="false" :title="dataForm.userId ? $t('common.editBtn') : $t('common.addBtn')"
                 draggable v-model="visible">
        <el-form :model="dataForm" :rules="dataRules" label-width="90px" ref="dataFormRef" v-loading="loading">
          <el-row :gutter="20">
            <el-col :span="12" class="mb20">
              <el-form-item :label="$t('left.processCode')" prop="processCode">
                <el-select filterable clearable  v-model="dataForm.processId" @change="processChange" >
                  <el-option :key="item.id" :label="item.processCode" :value="item.id" v-for="item in processData">
                    <span style="float:left;">{{ item.processName }}</span>
                    <span style="float:left;margin-left: 10px">{{ item.processCode }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12" class="mb20">
              <el-form-item :label="$t('left.productionLineCode')" prop="productionLineCode">
                <el-select filterable clearable  v-model="dataForm.productionLineCode">
                  <el-option :key="item.id" :label="item.productionLineName" :value="item.productionLineCode" v-for="item in productionLineData">
                    <span style="float:left;margin-left: 10px">{{ item.productionLineCode }}</span>
                    <span style="float:left;">{{ item.productionLineName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="12" class="mb20">
            <el-form-item :label="$t('left.materialCode')" prop="materialCode">
              <el-select filterable clearable  v-model="dataForm.materialCode" remote :remote-method="getMaterial">
                <el-option :key="item.id" :label="item.materialCode" :value="item.materialCode" v-for="item in materialData">
                  <span style="float:left;">{{ item.realMaterialName }}</span>
                  <span style="float:left;margin-left: 10px">{{ item.materialCode }}</span>
                  <span style="float:left;margin-left: 10px">{{ item.specification }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12" class="mb20">
            <el-form-item :label="$t('left.leftTime')" prop="leftTime">
              <el-date-picker
                v-model="dataForm.leftTime"
                type="date"
                style="width: 100%;"/>
            </el-form-item>
          </el-col>
            
            <el-col :span="12" class="mb20">
              <el-form-item :label="$t('left.leftQty')" prop="leftQty">
                <el-input v-model="dataForm.leftQty" type="number"></el-input>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
        <template #footer>
                  <span class="dialog-footer">
                      <el-button @click="visible = false" icon="close">{{ $t('common.cancelButtonText') }}</el-button>
                      <el-button @click="onSubmit" type="primary" icon="check" :disabled="loading">{{
                $t('common.confirmButtonText')
              }}</el-button>
                  </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts" name="spDialog" setup>
  import {useMessage} from '/@/hooks/message';
  import {getAllMaterials, getAllProcess} from '/@/api/platform/wms/reprintbarcode';
  import {
    addOrUpdateLeftMaterial,
    GetLeftmaterial,
    getProductionlineByProcessId
  } from '/@/api/platform/report/leftmaterial';
  import { getAllMaterialsForNameOrCode} from '/@/api/platform/digital/basProcess'
  import {reactive, ref} from 'vue';
  import {useI18n} from 'vue-i18n';
  // 通知父组件刷新
  const emit = defineEmits(['refresh']);
  // 定义变量内容
  const dataFormRef = ref();
  const visible = ref(false);
  const materialData = ref<any[]>([]);
  const processData = ref<any[]>([]);
  const productionLineData = ref<any[]>([]);
    
  const loading = ref(false);
  const size = ref<'default' | 'large' | 'small'>('default');
  const {t} = useI18n();
  
  const dataForm = reactive({
  
  });
  
  const dataRules = ref({
    processId: [
      {required: true, message: t('bar.cannotEmpty'), trigger: 'blur'},
    ],
    productionLineCode: [
      {required: true, message: t('bar.cannotEmpty'), trigger: 'blur'},
    ],
    materialCode: [
      {required: true, message: t('bar.cannotEmpty'), trigger: 'blur'},
    ],
    leftTime: [
      {required: true, message: t('bar.cannotEmpty'), trigger: 'blur'},
    ],
    leftQty: [
      {required: true, message: t('bar.cannotEmpty'), trigger: 'blur'},
    ],
  });
  
  // 打开弹窗
  const openDialog = async (id: string) => {
    visible.value = true;

    // 重置表单数据
    nextTick(() => {
      dataFormRef.value?.resetFields();
      //重置产线数据，加载工序后再加载产线
      productionLineData.value=null;
      dataForm.id=0;
      dataForm.processId=null;
    });
    
    //编辑，字段赋值
    if(id){
        await GetLeftmaterial({"Id":id}).then((res)=>{
            Object.assign(dataForm, res.data);
            processChange(res.data.processId);
        })
        
    }
    getMaterials();
    getProcess();

  };

  //工序变更
  const processChange=(value)=>{
    if(value==''){
      dataForm.processCode=null;
      return;
    }
    getProductionlineByProcessId({"Id":value}).then((res)=>{
        productionLineData.value=res.data;
    })
  }
  // 获取物料
  const getMaterials = () => {
    getAllMaterials().then((res) => {
      materialData.value =res.data;
      
    });
  };
  
  //获取工序
  const getProcess=()=>{
    getAllProcess({}).then((res) => {
      processData.value =res.data;
      
    });
  }
  // 提交
  const onSubmit = async () => {
    const valid = await dataFormRef.value.validate().catch(() => {
    });
    if (!valid) return false;
  
    try {
        loading.value = true;
        await addOrUpdateLeftMaterial(dataForm).then((res)=>{
          if(!res.ok){
            useMessage().error(res.data);
          }
        });
        visible.value = false; // 关闭弹窗
        emit('refresh');
    } catch (error: any) {
      useMessage().error(error.msg);
    } finally {
      loading.value = false;
    }
  };
  const getMaterial = (query: string) => {
    getAllMaterialsForNameOrCode({
        "materialCode": query
    }).then((res: any) => {
        if (res.code == 0) {
          materialData.value = res.data
        }
    })
}
  // 暴露变量
  defineExpose({
    openDialog,
  });
  </script>
  